/*
 * @lc app=leetcode.cn id=120 lang=cpp
 *
 * [120] 三角形最小路径和
 */

// @lc code=start
class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        const int m = triangle.size();
        const int n = triangle[m-1].size();
        vector<int> dp(n, 0);
        vector<int> tmp(n,0);
        dp[0] = triangle[0][0];

        if(m == 1) return dp[0];

        for(int i = 0; i < m - 1; i++)
        {
            tmp[0] = dp[0] + triangle[i+1][0];

            const int n_tmp = triangle[i+1].size();

            for(int j = 1; j < n_tmp - 1; j++)
            {
                tmp[j] = min(dp[j], dp[j-1]) + triangle[i+1][j];
            }
            
            tmp[n_tmp - 1] = dp[n_tmp - 2] + triangle[i+1][n_tmp - 1];
            tmp.swap(dp);
        }
        
        int ans = dp[0];
        for(int i = 1; i < dp.size(); i++)
        {
            ans = min(ans, dp[i]);
        }
        return ans;
    }
};
// @lc code=end

